﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.DeviceEntity.Model;
using KingRoad.EPM.Web.Areas.Device.Models;
using KingRoad.EPM.Entity;
using DotNet.Service;
using DotNet.Model.MyEntity;
using KingRoad.EPM.DeviceBLL.UIRules;
using System.Dynamic;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.SS.Util;
using System.IO;
namespace KingRoad.EPM.Web.Areas.Device.Controllers
{
    public class RoadwayController : BaseController
    {

        public ActionResult Index()
        {

            return View();
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="placId">部门id</param>
        /// <returns></returns>
        public ActionResult List(string placId, string Code)
        {
            ViewBag.PlacId = placId;
            ViewBag.Code = Code;
            Base_Organize oInfo = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(placId);
            ViewBag.danwei = oInfo.FullName;
            string sql = " PlacId=" + placId;
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var rlist = BllRoadwayUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Id", out totalRecord, sql, "desc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new RoadwayModel { list = rlist });
        }

        /// <summary>
        /// 列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.iput_name = Request.Form["iput_name"];
            ViewBag.iput_code = Request.Form["iput_code"];
            ViewBag.PlacId = Request.Form["input_placId"];
            ViewBag.Code = Request.Form["Code"];
            Base_Organize oInfo = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(ViewBag.PlacId);
            ViewBag.danwei = oInfo.FullName;
            string sql = " 1=1 ";
            if (ViewBag.iput_name != "")
                sql += " and RName like '%" + ViewBag.iput_name + "%' ";
            if (ViewBag.iput_code != "")
                sql += " and Code like '%" + ViewBag.iput_code + "%' ";
            if (ViewBag.PlacId != "")
                sql += " and PlacId= " + ViewBag.PlacId + " ";
            var rlist = BllRoadwayUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Id", out totalRecord, sql, "desc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("List", new RoadwayModel { list = rlist });
        }

        public ActionResult Create(string placId)
        {
            Base_Organize oInfo = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(placId);
            ViewBag.placId = placId;
            ViewBag.placeName = oInfo.FullName;
            return View();
        }

        public JsonResult CreateData(RoadwayModel vm)
        {
            bool isScuess = true;
            try
            {
                BllRoadwayUIRule.InsertEntity(vm.info);
            }
            catch (Exception ex)
            {
                isScuess = false;
            }

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "Device.Roadway.List",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        public ActionResult Detail(int id)
        {
            BllRoadwayInfo rInfo = BllRoadwayUIRule.GetEntityById(id);

            ViewBag.placId = rInfo.PlacId;

            return View(new RoadwayModel { info = rInfo });
        }

        public ActionResult Edit(int id)
        {
            BllRoadwayInfo rInfo = BllRoadwayUIRule.GetEntityById(id);
            Base_Organize oInfo = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(rInfo.PlacId.ToString());
            ViewBag.placId = rInfo.PlacId;
            ViewBag.placeName = oInfo.FullName;
            return View(new RoadwayModel { info = rInfo });
        }

        public JsonResult EditData(RoadwayModel vm)
        {
            bool isScuess = true;
            try
            {
                BllRoadwayUIRule.UpdateEntity(vm.info);
            }
            catch (Exception ex)
            {
                isScuess = false;
            }

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "修改成功",
                    navTabId = "Device.Roadway.List",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        public JsonResult Delete(int id)
        {
            bool isScuess = true;
            try
            {
                var st = BllRoadwayUIRule.DeleteEntity(id);
            }
            catch (Exception ex)
            {
                isScuess = false;
            }
            dynamic jsonReturn = new ExpandoObject();
            //删除成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "cdxx_list",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// Excel导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public JsonResult ImportExcelFile(HttpPostedFileBase FileData)
        {
            bool isScuess = true;
            try
            {
                if (FileData != null)
                {
                    string tempFileName = FileData.FileName;
                    string fileExt = Path.GetExtension(tempFileName).ToLower();
                    string fileName = Guid.NewGuid().ToString() + fileExt;
                    string tempPath = "/TempleterFilePath";
                    if (!tempPath.EndsWith("/"))
                        tempPath += "/";
                    tempPath = Server.MapPath(tempPath);
                    if (!Directory.Exists(tempPath))
                        Directory.CreateDirectory(tempPath);
                    tempPath = Path.Combine(tempPath, fileName);
                    FileData.SaveAs(tempPath);
                    if (string.IsNullOrWhiteSpace(tempPath) || !System.IO.File.Exists(tempPath))
                    {
                        throw new Exception("导入文件不存在");
                    }
                    string Section = Request.QueryString["Section"];
                    HSSFWorkbook hssfworkbook;

                    //读取文件流
                    using (FileStream fs = System.IO.File.OpenRead(tempPath))
                    {
                        hssfworkbook = new HSSFWorkbook(fs);
                        //获取第一个工作簿
                        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                        {
                            //获取第一行
                            IRow headerRow = sheet.GetRow(0);
                            //列数
                            int cellCount = headerRow.LastCellNum;
                            //行数
                            int rowCount = sheet.LastRowNum;
                            //循环行
                            for (int i = 1; i <= rowCount; i++)
                            {
                                IRow row = sheet.GetRow(i);
                                //整体风险评估台账
                                //ScmRiskassessInfo info = new ScmRiskassessInfo();
                                BllRoadwayInfo info = new BllRoadwayInfo();
                                //读取该行信息
                                info.PlacId = Convert.ToInt32(Section);
                                info.RName = GetCellValue(row.GetCell(0));
                                info.Code = GetCellValue(row.GetCell(1));
                                info.Lon = string.IsNullOrEmpty(GetCellValue(row.GetCell(2))) ? 0 : Convert.ToDecimal(GetCellValue(row.GetCell(2)));
                                info.Lat = string.IsNullOrEmpty(GetCellValue(row.GetCell(3))) ? 0 : Convert.ToDecimal(GetCellValue(row.GetCell(3)));

                                //向数据库插入数据
                                BllRoadwayUIRule.InsertEntity(info);
                            }
                        }
                    }
                    //删除临时文件
                    System.IO.File.Delete(tempPath);
                }
            }
            catch (Exception ex)
            {
                isScuess = false;
            }
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "导入成功",
                    navTabId = "",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "导入失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// Excel导出
        /// </summary>
        /// <returns></returns>
        public FileResult Excel(string PlacId, string danwei)
        {
            //获取list数据           
            var list = BllRoadwayUIRule.GetEntityListBySql(" PlacId=" + PlacId);
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //列宽度

            sheet1.SetColumnWidth(0, 8 * 256);
            sheet1.SetColumnWidth(1, 20 * 256);
            sheet1.SetColumnWidth(2, 20 * 256);
            sheet1.SetColumnWidth(3, 12 * 256);
            sheet1.SetColumnWidth(4, 12 * 256);
            //设置第一行
            IRow row0 = sheet1.CreateRow(0);
            //行高
            row0.Height = 30 * 20;
            //合并单元格
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
            //创建单元格
            CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), danwei + "车道信息");


            //给sheet1添加第行的头部标题
            IRow row2 = sheet1.CreateRow(1);
            //行高
            row2.Height = 25 * 20;
            CreateCell(row2, 0, Getcellstyle(book, "center", true, 11, 600), "序号");
            CreateCell(row2, 1, Getcellstyle(book, "center", true, 11, 600), "车道名称");
            CreateCell(row2, 2, Getcellstyle(book, "center", true, 11, 600), "车道编号");
            CreateCell(row2, 3, Getcellstyle(book, "center", true, 11, 600), "经度");
            CreateCell(row2, 4, Getcellstyle(book, "center", true, 11, 600), "纬度");

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 2);
                CreateCell(rowtemp, 0, Getcellstyle(book), (i + 1).ToString());
                CreateCell(rowtemp, 1, Getcellstyle(book), list[i].RName);
                CreateCell(rowtemp, 2, Getcellstyle(book), list[i].Code);
                CreateCell(rowtemp, 3, Getcellstyle(book), list[i].Lon.ToString());
                CreateCell(rowtemp, 4, Getcellstyle(book), list[i].Lat.ToString());
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            string fileName = HttpUtility.UrlEncode("车道信息.xls", Encoding.GetEncoding("UTF-8"));
            return File(ms, "application/vnd.ms-excel", fileName);

        }
    }
}
